import logging
import json
import os
from catalog.dip_catalog import DipCatalog
from patient.patient import PatientInfo
from series.rules.dip_series_rules import DIPGroupRules
# 这个文件不需要Flask

# 移除APIResponse导入，因为这个文件不需要Flask

logger = logging.getLogger(__name__)


# 配置日志
def setup_logger():
    # 创建logs目录
    log_dir = "logs"
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # 配置日志格式
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(os.path.join(log_dir, 'dip_group_rules.log'), encoding='utf-8'),
            logging.StreamHandler()
        ]
    )
    return logging.getLogger(__name__)


logger = setup_logger()
class DipSeriesEntrance:
    def __init__(self):
        self.entrance()  # 调用类方法

    def entrance(self):
        logger.info("执行AI 入口方法")
        dip_group_rules= DIPGroupRules()
        dipCatalog =DipCatalog()
        patient_info =PatientInfo()
        patient_json= patient_info.read_patient_info_json();
        # 转成 Python 字典
        patient_dict = json.loads(patient_json)
        results = []
        
        for patient_row in patient_dict.get("data", []):
            core_catalog_json = dipCatalog.load_core_catalog("诊断编码", patient_row['诊断编码'])
            # if(core_catalog_json["data"] == None):
            #     return {
            #         "status": "success",
            #         "message": "找不到主诊断",
            #         "data": ""
            #     }
            # 执行AI分析，获取结构化结果
            ai_result = dip_group_rules.execute_ai(patient_row, core_catalog_json)
            
            # 检查是否有错误
            if isinstance(ai_result, dict) and "错误" in ai_result:
                print(f"AI调用失败: {ai_result['错误']}")
                continue  # 跳过这个患者，继续处理下一个
            # 打印结果
            print("="*50)
            print(f"患者诊断编码: {patient_row['诊断编码']}")
            print("AI分析结果:")
            print("\n解析结果:")
            parsed_data = ai_result['解析结果']
            for key, value in parsed_data.items():
                print(f"  {key}: {value}")
            
            print("="*50)
            
            # 收集结果
            results.append({
                "患者诊断编码": patient_row['诊断编码'],
                "解析结果": parsed_data
            })
        
        return {
            "status": "success",
            "message": "DIP分析完成",
            "data": results
        }


def main():
    dipSeries = DipSeriesEntrance()


if __name__ == "__main__":
    main()